#include "wppostgraphicslistitem.h"
#include "WPData.h"
#include "themedatastorage.h"
#include "HtmlPainter.h"

#include <QPoint>
#include <QRect>
#include <QPainter>

// static member
WPPostGraphicsListItem::Geometry WPPostGraphicsListItem::iGeometry;

WPPostGraphicsListItem::WPPostGraphicsListItem(WPPost aPost, BusyIndicator& aBusyIndicator, ThemeData& aThemeData)
    : WPGraphicsListItem(aBusyIndicator, aThemeData)
    , iPost(aPost)
{
    setObjectName("WPPostListItem");
    //: %1 is a name and %2 is a date, e.g. by User 04/01 08:31
    iAuthorAndDate = tr("by %1 %2").arg(iPost->iWpAuthorDisplayName).arg(aPost->GetShortLocalTimeString());

    int commentCount = iPost->GetComments().count();

    if (commentCount == 1) {
        iCommentsText = tr("1 comment");
    } else {
        iCommentsText = tr("%1 comments") .arg(commentCount);
    }
    
    iTitle = new HtmlPainter(HtmlPainter::Content, iThemeData);
    iTitle->setContent(iPost->iTitle);
}

WPPostGraphicsListItem::~WPPostGraphicsListItem()
{
    delete iTitle;
}

bool WPPostGraphicsListItem::operator<(WPPostGraphicsListItem const & other)
{
    return (iPost->GetLocalTime() < other.iPost->GetLocalTime());
}

WPPost WPPostGraphicsListItem::GetPost() const
{
    return iPost;
}

void WPPostGraphicsListItem::paintContent(QPainter* painter, const QStyleOptionGraphicsItem* /*option*/, QWidget* /*widget*/)
{
    painter->setPen(Qt::black);

    iTitle->setOneLineMode(iGeometry.iTitle.width());
    iTitle->paint(painter, iGeometry.iTitle);

    painter->setFont(*iThemeData.iListInfoFont);
    painter->drawText(iGeometry.iAuthorAndDate, iAuthorAndDate);
    painter->drawText(iGeometry.iCommentInfo, iCommentsText);
}

bool WPPostGraphicsListItem::IsBusy()
{
    return iPost->IsBusy();
}

bool WPPostGraphicsListItem::HasError()
{
    return iPost->iError;
}

void WPPostGraphicsListItem::handleGeomeryChange()
{
    iGeometry.update(*this);
    setMinimumHeight(iGeometry.height());
}
        
void WPPostGraphicsListItem::Geometry::update (WPPostGraphicsListItem & parent)
{
    const QSizeF size = parent.size();
    const ThemeData &theme = parent.iThemeData;
    
    if (iCachedSize == size)
        // fresh
        return;
    else
        iCachedSize = size;

    int const itemPadding = theme.iListItemInternalPadding;
    int const vPadding = theme.iListItemContentVMargin;
    int const hPadding = theme.iListItemContentHMargin;
    int const width = size.width() - 2 * hPadding;
    
    // Font metrics
    QFontMetrics infoFont (*theme.iListInfoFont);

    iTitle.setRect(hPadding, vPadding, width, parent.iTitle->fontMetrics().height());
    iAuthorAndDate.setRect(hPadding, iTitle.bottom() + itemPadding, width, infoFont.height());
    iCommentInfo.setRect(hPadding, iAuthorAndDate.bottom() + itemPadding, width, infoFont.height());

    iHeight = iCommentInfo.bottom() + vPadding;
}
